package com.example.hotelback.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.hotelback.entity.Params;
import com.example.hotelback.entity.User;
import com.example.hotelback.exception.CustomException;
import com.example.hotelback.service.UserService;
import com.example.hotelback.utils.JwtUtils;
import com.example.hotelback.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    @ResponseBody // 返回给浏览器
    public Result login(@RequestBody User user) {
        try {
            User loginUser = userService.findByCond(user.getName(), user.getPassword());
            String token = JwtUtils.generateToken(loginUser.getId(), loginUser.getName());
            loginUser.setToken(token);
            return Result.success(loginUser);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 用户查看个人信息
     * @param id
     * @return
     */
    @ApiOperation("用户查看个人信息")
    @GetMapping("/find")
    @ResponseBody
    public Result find(int id) {
        User user = userService.findById(id); // 找到的user是数据表中的，没有token
        return Result.success(user); // 能登录就一定有对应管理员
    }

    /**
     * 注册
     * @param tempUser
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User tempUser) {
        try {
            userService.register(tempUser);
            return Result.success();
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 管理员查看所有用户信息
     * @return
     */
    @ApiOperation("管理员查看所有用户信息")
    @GetMapping("/findAllUsers")
    @ResponseBody
    public Result findAllUsers(Params params) {
        IPage<User> iPage = userService.findAllUsers(params);
        return Result.success(iPage);
    }

    /**
     * 用户修改个人信息（修改后端接收JSON数据）
     * @param payload
     * @return
     */
    @ApiOperation("用户修改个人信息")
    @PostMapping("/update")
    @ResponseBody
//    public Result update(int id, User newUser) { // 获取表单类型的数据
//        userService.update(id, newUser);
//        return Result.success();
//    }
    public Result update(@RequestBody Map<String, Object> payload) { // 获取JSON数据
        Integer id = (Integer) payload.get("id");
        User newUser = new ObjectMapper().convertValue(payload.get("newUser"), User.class);
        userService.update(id, newUser);
        return Result.success();
    }
}
